<template>
  <div class="auto">
    <validator name='v'>
      <form novalidate class="form-horizontal">
        <p class="bg-info text-center" style="padding: 8px;">发卡售气</p>
        <div class="row">
          <div class="form-group form-input-group col-sm-4">
            <label for="f_paytype" class=" col-sm-2 control-label">付款方式:</label>
            <div class="col-sm-2">
              <v-select id="f_payment"
                        v-model="f_payment"
                        placeholder='请选择'
                        :value.sync="model.f_payment"
                        :options='paytype'
                        close-on-select clear-button>
            </div>
          </div>
          <div class="form-group form-input-group col-sm-4"
               :class="[$v.f_pregas.required ? 'has-error' : 'has-success']">
            <label for="f_pregas" class=" col-sm-2 control-label">预购气量:</label>
            <input class="form-control col-sm-2" type="number"
                   @blur="pregas()" v-model="model.f_pregas"
                   v-validate:f_pregas='{required: true }' placeholder="预购气量"
                   v-next-el='sk' :disabled="row.f_collection_type !== '按气量'">
          </div>

          <div class="form-group form-input-group col-sm-4">
            <label for="f_preamount" class=" col-sm-2 control-label">预购金额:</label>
            <input class="form-control col-sm-2" type="number" v-model="model.f_preamount"
                   v-scale="[model.f_preamount, 2]" placeholder="预购金额" disabled>
          </div>
        </div>
        <div class="row" style="margin-top:6px;">
          <div class="form-group form-input-group col-sm-4">
            <!-- <print-style :print.sync='model.f_print'></print-style> -->
            <label for="f_print" class="control-label col-sm-2">打印格式:</label>
            <div class="col-sm-2">
              <v-select id="print"
                        v-model="f_print"
                        placeholder='请选择'
                        :value.sync="model.f_print"
                        :options='printstyle'
                        close-on-select clear-button>
            </div>
          </div>
          <div class="form-group form-input-group col-sm-4">
          </div>

          <div class="from-group  form-input-group col-sm-4"
               :class="[$v.f_temp_amount.required ? 'has-error' : 'has-success']">
            <label for="f_temp_amount" v-if="row.f_collection_type === '按气量'"
                   class=" col-sm-2 control-label">应收金额:</label>
            <label for="f_temp_amount" v-if="row.f_collection_type === '按金额'"
                   class=" col-sm-2 control-label">本次缴费:</label>
            <input class="form-control col-sm-2" type="number"
                   @blur="preamount()" v-model="model.f_temp_amount"
                   v-validate:f_temp_amount='{required: true }' placeholder="应收金额"
                   v-next-el='sk' v-scale="[model.f_temp_amount, 2]" :disabled="row.f_collection_type !== '按金额'">
          </div>
        </div>
        <div class="row">
          <div class="form-group form-input-group col-sm-4">
            <label for="f_balance" class=" col-sm-1 control-label">上期结余:</label>
            <input class="form-control col-sm-2" type="number" v-model="model.f_balance"
                   v-scale="[model.f_balance, 2]" placeholder="上期结余" disabled>
          </div>
          <div class="from-group form-input-group col-sm-4">
            <label for="f_curbalance" class="col-sm-1 control-label">本期结余:</label>
            <input class="form-control col-sm-2" type="number" v-model="curbalance"
                   v-scale="[model.f_curbalance, 2]" placeholder="本期结余" disabled>
          </div>

          <div class="form-group form-input-group col-sm-4" v-if="row.f_collection_type === '按气量'"
               :class="[$v.f_collection.required ? 'has-error' : 'has-success']">
            <label for="f_collection" class=" col-sm-2 control-label">收款:</label>
            <input id="f_collection" class="form-control col-sm-2" type="number" v-model="model.f_collection"
                   v-validate:f_collection='{required: true, dctest: [Math.trunc(model.f_temp_amount), ">=" ] }'
                   v-el:sk v-scale="[model.f_collection, 2]">
          </div>
          <div class="form-group form-input-group col-sm-4" v-if="row.f_collection_type === '按金额'">
            <label for="f_collection" class=" col-sm-2 control-label">收款:</label>
            <input id="f_collection" class="form-control col-sm-2" type="number" v-model="model.f_collection"
                   v-el:sk v-scale="[model.f_collection, 2]" :disabled='true'>
          </div>
        </div>
        <div class="row" style="margin-top:5px;">
          <div class="col-sm-9 form-input-group">
            <label for="f_curbalance" class="col-sm-2 control-label">备注:</label>
            <input class="form-control" type="text" v-model="row.f_comments" placeholder="<无备注>" disabled>
          </div>
          <div class="col-sm-3 form-input-group">
            <span v-if="$v.f_collection.dctest" style="color:red ">收款不能小于应收金额</span>
          </div>
        </div>
        <div class="row">
          <div class="col-sm-4 col-sm-offset-8">
            <strong>计算公式:{{calculatedetail ? calculatedetail : ' 暂无'}}</strong>
          </div>
        </div>
        <div class="row">
          <div class="col-sm-5" v-if="row.f_collection_type === '按气量'">
            <strong style="color:green">温馨提示: 此气表品牌是按气量收费!!</strong>
          </div>
          <div class="col-sm-4" v-if="row.f_collection_type === '按金额'">
            <strong style="color:green">温馨提示: 此气表品牌是按金额收费!!</strong>
          </div>
        </div>
      </form>
      <print-bill :show="print" v-ref:printbill v-on:toggle="close" :data='row'></print-bill>
      <div style="text-align:right;margin-top:80px;margin-right:50px;">
        <button class="btn btn-success" @click="confirm()" :disabled='!$v.valid'>
          确&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;认
        </button>
        <button class="btn btn-default" @click="clean()" style="width:80px;margin-left:20px;">取&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;消</button>
      </div>
    </validator>
  </div>
</template>
<script>
  /**
   *综合业务
   *发卡售气组件
   */
  import AppData from '../../../../../stores/AppData'
  import co from 'co'

  let preamountGen = function* (self) {
    let temp = (self.model.f_temp_amount - 0) + (self.model.f_balance - 0)
    let getGas = yield self.$CommonService.feeCalculate(self.model, temp)
    let getAmount = null
    if (getGas.data.gas) {
      if (self.row.f_isdecimal === '是') {
        self.model.f_preamount = temp
        let tempGas = 0
        if (self.row.f_alias === 'QiaoSong') {
          tempGas = (getGas.data.gas - 0).toFixed(2)
          self.model.f_pregas = (getGas.data.gas - 0).toFixed(1)
        } else {
          self.model.f_pregas = (getGas.data.gas - 0).toFixed(2)
        }
        console.log('3333333333333333', tempGas)
        getAmount = yield self.$CommonService.gasCalculate(self.model, tempGas > 0 ? tempGas : self.model.f_pregas)
      } else {
        self.model.f_pregas = parseInt(getGas.data.gas - 0)
        getAmount = yield self.$CommonService.gasCalculate(self.model, self.model.f_pregas)
        self.model.f_preamount = getAmount.data.chargenum
      }
    }

    self.model.chargeprice = getAmount.data.chargeprice
    Object.assign(self.model, self.model, getAmount.data)
    console.log('发卡收起。。。11', self.model.f_temp_amount)
    self.model.f_collection = Math.trunc(self.model.f_temp_amount)
    console.log('发卡收起。。。22', self.model.f_collection)
    self.calText(getAmount.data.chargeprice)
  }

  export default {
    title: '发卡售气',
    data() {
      return {
        model: {
          f_stairprice_id: '',
          f_payment: ['现金缴费'],
          f_pregas: '',
          f_preamount: 0,
          f_temp_amount: '',
          f_balance: 0,
          f_curbalance: 0,
          f_collection: '',
          chargeprice: [],
          f_print: ['国税发票'],
          f_meter_type: ''
        },
        print: false,
        cardallot: null,
        calculatedetail: ''
      }
    },
    props: ['row'],
    ready() {
      this.model.f_price_id = this.row.f_price_id
      this.model.f_user_id = this.row.f_user_id
      this.model.f_userinfo_id = this.row.f_userinfo_id
      // this.model.f_pregas = AppData.getSingleValue('默认购气量')
      if (AppData.getSingleValue('是否启用发卡管理')) {
        this.$CardManageService.getCardNumber()
          .then((res) => {
            this.cardallot = Object.assign({}, this.cardallot, res.data)
          })
      }
      // this.pregas()
    },
    watch: {
      'row'(val) {
        this.model.f_balance = val.f_balance
        // this.model.f_pregas = AppData.getSingleValue('默认购气量')
      }
    },
    methods: {
      confirm() {
        this.model.f_curbalance = this.curbalance
        this.model.f_payment = this.model.f_payment[0]
        if (AppData.getSingleValue('是否启用发卡管理')) {
          this.$showMessage(`您现在可以使用的卡号为:${this.cardallot.f_now_number},卡类型为:${this.cardallot.f_card_type},请确定您即将使用的是本卡号`,
            ['confirm', 'cancel']).then((res) => {
            if (res === 'confirm') {
              this.writeCard()
            }
          })
        } else {
          this.writeCard()
          // console.log('保存了。，。，。', this.model, this.row)
        }
      },
      // 写卡保存数据 迁至此处
      writeCard() {
        console.log('开始发卡售气。。')
        this.$CardService.initCard(this.model, this.row, this.cardallot)
          .then(
            (res) => {
              console.log('发卡售气开始打票', res.data.id)
              this.row.id = res.data.id
              this.row.f_bill_type = '卡表收费'
              this.row.f_bill_style = this.model.f_print[0]
              this.row.f_preamount = this.model.f_preamount
              this.row.f_collection = this.model.f_collection
              this.print = true
              this.$refs.printbill.cardbill.search(res.data.id)
              // this.$dispatch('success', '发卡售气', this.row, res)
            }
          ).catch(
          (error) => {
            if (error.status === 603) {
              this.$error('重复提交')
              return
            }
            this.$dispatch('error', '发卡售气', this.row, error)
          }
        )
      },
      clean() {
        this.$info('取消操作')
        this.$dispatch('refresh', this.row)
      },
      pregas() {
        if (this.model.f_pregas) {
          if (this.row.f_isdecimal === '是') {
            this.model.f_pregas = (this.model.f_pregas - 0).toFixed(2)
          } else {
            this.model.f_pregas = (this.model.f_pregas - 0).toFixed(0)
          }
          this.model.f_meter_type = this.row.f_meter_type
          console.log('发卡售气，，，，', this.model, this.row)
          this.$CommonService.gasCalculate(this.model, this.model.f_pregas).then((res) => {
            // let l = res.da
            this.model.f_temp_amount = res.data.chargenum
            this.model.f_preamount = res.data.chargenum
            Object.assign(this.model, this.model, res.data)
            this.model.chargeprice = res.data.chargeprice
            this.model.f_temp_amount = (this.model.f_preamount - 0) - (this.model.f_balance - 0)
            this.model.f_collection = Math.trunc(this.model.f_temp_amount)
            this.calText(res.data.chargeprice)
          }).catch((error) => {
            this.$dispatch('error', '发卡售气', this.model, error)
          })
        }
      },
      preamount() {
        if (this.model.f_temp_amount) {
          try {
            this.model.f_meter_type = this.row.f_meter_type
            co(preamountGen(this))
          } catch (error) {
            this.$dispatch('error', '发卡售气', this.model, error)
          }
          // this.$CommonService.feeCalculate(this.model, this.model.f_preamount).then((res) => {
          //   this.model.f_pregas = res.data.gas
          //   this.model.chargeprice = res.data.chargeprice
          //   Object.assign(this.model, this.model, res.data)
          //   this.calculate()
          //   this.calText(res.data.chargeprice)
          // }).catch((error) => {
          //   this.$dispatch('error', '发卡售气', this.model, error)
          // })
        }
      },
      calText(val) {
        let str = ''
        val.forEach((item) => {
          str = str + item.f_price + ' x ' + item.f_gas + '+'
        })
        str = str.slice(0, str.length - 1)
        this.calculatedetail = str
      },
      close() {
        this.showprint = false
        this.print = false
        this.clean()
      }
    },
    computed: {
      'curbalance'() {
        if (this.model.f_preamount !== '' && this.model.f_temp_amount !== '') {
          if (this.row.f_collection_type === '按金额') {
            return ((this.model.f_collection - 0) + (this.model.f_balance - 0) - (this.model.f_preamount - 0)).toFixed(2)
          } else {
            return ((this.model.f_collection - 0) - (this.model.f_temp_amount - 0)).toFixed(2)
          }
        } else {
          return 0
        }
      },
      paytype() {
        return AppData.getParam('付款方式')
      },
      printstyle() {
        return AppData.getParam('打印格式')
      }
    }
  }
</script>

<style>
</style>
